<template>
  <div class="container">
    <header>
      <van-icon name="arrow-left" @click="golin" />
      新型冠状病毒测试
    </header>

    <main v-if="flag">
      <div class="top">
        <div class="top1">量表名称</div>
        <div class="content">
          <van-progress :percentage="prersent"></van-progress>
          <div class="th">
            <i>{{ num }}</i
            >/
            <em>{{ topic.length }}</em>
          </div>
          <div class="qus">
            <div class="title">
              <span>{{ num }}</span
              >.
              <span>{{ qusetion }}</span>
              <span v-if="timu['answer_type'] == 1">(单选)</span>
              <span v-else>(多选)</span>
            </div>
            <div class="a1">
              <!-- 单选1 多选2 -->
              <template v-if="timu['answer_type'] == 1">
                <van-radio-group v-model="timu.select">
                  <van-radio
                    v-for="(item, index) in option"
                    :key="index"
                    :name="index"
                    @click="chooseAnswer()"
                    >{{ item }}</van-radio
                  >
                </van-radio-group>
              </template>

              <template v-else>
                <div>
                  <van-checkbox-group
                    v-model="selected"
                    @change="chooseAnswer()"
                  >
                    <van-checkbox
                      v-for="(item, index) in option"
                      :key="index"
                      >{{ item }}</van-checkbox
                    >
                  </van-checkbox-group>
                </div>
              </template>
            </div>
          </div>
        </div>

        <div class="jh">
          <input
            type="button"
            value="上一题"
            class="left"
            :class="{ active: num > 1 }"
            @click="pre"
          />
          <input
            :disabled="disabled"
            type="button"
            value="下一题"
            class="right active show"
            @click="next()"
            v-if="num < topic.length"
          />
          <input
            v-else
            type="button"
            value="提交"
            class="get active"
            @click="submit"
          />
        </div>
      </div>
    </main>
    <van-dialog title="本次得分" :visible.sync="dialogVisible" width="70%">
      <h1>{{ countscore }}分</h1>
      <span slot="footer" class="dialog-footer">
        <van-button type="info" @click="close">查看评价</van-button>
      </span>
    </van-dialog>
  </div>
</template>

<script>
import XLSX from 'xlsx'
import transformSheets from '../../api/readxlsx'
export default {
  data() {
    return {
      countscore: '',
      dialogVisible: false,
      selected: [],
      data: [
        { id: 1, name: 1 },
        { id: 2, name: 2 }
      ],
      ruleForm: {
        name: '',
        region: '',
        date1: '',
        date2: '',
        delivery: false,
        type: [],
        resource: '',
        desc: ''
      },
      name: this.$route.query.name,
      topic: [],
      num: 1,
      qusetion: '',
      option: '',
      timu: '',
      prersent: 0,
      flag: true,
      starttime: '',
      disabled: true,
      content: ''
    }
  },
  created() {
    this.$api.questionapi
      .getExcel()
      .then((result) => {
        var data = new Uint8Array(result.data)
        console.log(result, data)
        var wb = XLSX.read(data, { type: 'array' })
        console.log(wb)
        var sheets = wb.Sheets
        var content = transformSheets(sheets)
        var title = content[2]
        const spliceArr = content.slice(3)
        console.log(spliceArr)
        var jsondata = []
        spliceArr.map((item, index) => {
          var obj = {}
          if (item.length == title.length) {
          } else {
            var a = title.length - item.length
            switch (a) {
              case 1:
                item.splice(8, 0, 'null')
                break
              case 2:
                item.splice(7, 0, 'null')
                item.splice(8, 0, 'null')
                break

              default:
                break
            }
          }
          item.map((item1, index1) => {
            obj[title[index1]] = item1
          })
          jsondata.push(obj)
        })
        jsondata.map((item2, index2) => {
          var answers = []
          var obj = {}
          if (item2['answer1'] !== 'null') {
            answers.push(item2['answer1'])
          }
          if (item2['answer2'] !== 'null') {
            answers.push(item2['answer2'])
          }
          if (item2['answer3'] !== 'null') {
            answers.push(item2['answer3'])
          }
          if (item2['answer4'] !== 'null') {
            answers.push(item2['answer4'])
          }

          item2['answers'] = answers
        })
        console.log(jsondata)
        this.topic = jsondata
        this.show(this.num)
      })
      .catch((err) => {
        console.log(err.response)
      })
  },
  methods: {
    close() {
      this.dialogVisible = false
      this.$router.push({
        path: '/cale',
        query: { countscore: this.countscore }
      })
    },
    golin() {
      this.$router.go(-1)
    },
    pre() {
      this.selected = []

      if (this.num > 1) {
        this.num--
        this.show(this.num)
      } else {
        alert('已是第一题')
      }
    },
    show(num) {
      var that = this
      var index = num
      var number = num / that.topic.length
      // 截取两位小数
      that.prersent = (number * 100).toFixed(2) - 0
      that.timu = that.topic[index - 1]
      console.log(that.timu)
      if (that.timu.answer_type == 2) {
        //    如果是多选而且有selects属性赋值给select 单选是直接获取到自己的selected
        if (that.timu['selected']) {
          that.selected = that.timu['selected']
          // console.log(that.selected);
        }
      }
      //   如果有选着过的设置disabnled
      if (that.timu['selected']) {
        that.disabled = false
      } else {
        that.disabled = true
      }
      // console.log(that.timu);
      that.qusetion = that.timu['question']
      that.option = that.timu['answers']
    },
    chooseAnswer() {
      // 只有选择了都有select的属性，可能为空值，没选一定没有这个属性 组件每一次都能从新得到新的值，不会和已选到的重合\
      var that = this
      that.disabled = false
      if (that.timu.type == 1) {
        var arr = []
        arr.push(that.timu.select)
        that.topic[that.num - 1]['selected'] = arr
      } else {
        that.topic[that.num - 1]['selected'] = that.selected
      }
      setTimeout(() => {
        that.next()
      }, 500)

      console.log(that.topic[that.num - 1], that.selected)
    },
    next() {
      if (this.num < this.topic.length) {
        this.selected = [] //不然会继承前面选着的select，每次清空。如果选着过渲染时show会加上赋值

        this.num++

        this.show(this.num)
      } else {
        this.$toast('最后一题请提交')
      }
    },
    submit() {
      var that = this
      var answers = []
      this.topic.map((item, index) => {
        if (item['selected'] && item['selected'].length > 0) {
          console.log(item.selected)
          answers.push(item.selected)
        } else {
          answers.push(null)
        }
      })

      var countscore = 0
      var answererr = []

      answers.map((item, index) => {
        // 找到单选格式的数组答案[2],成为[2.3,[2,3]]
        if (Array.isArray(item) && item.length == 1) {
          answers[index] = item[0]
        }
      })
      console.log(answers, this.topic)
      this.topic.map((item, index) => {
        //单选
        console.log(index, answers[index])
        if (item['type'] == 1) {
          if (item['right_key'] == answers[index]) {
            var score = item['score']
            countscore += score
          } else {
            // 选错了

            item['erranswer'] = answers[index]
            answererr.push(item)
          }
        } else {
          // 多选
          var arr2 = item['right_key'].split('|')
          if (arr2.sort().toString() == answers[index].sort().toString()) {
            var score = item['score']
            countscore += score
          } else {
            item['erranswer'] = answers[index]
            answererr.push(item)
          }
        }
      })
      console.log(countscore, answererr)

      // json变量转化成json字符串
      var jsonstr = JSON.stringify(answererr)
      // 存储json字符串
      window.localStorage.setItem('jsonkey', jsonstr)
      this.countscore = countscore

      this.$router.push({
        path: '/cale',
        query: { countscore: this.countscore }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.van-icon {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
  left: 10px;
  cursor: pointer;
}

.container {
  min-height: 768px;
  max-width: 768px;
  margin: 0 auto;
  background: url('../../assets/avoidtest/bj1@2x.png') no-repeat;
  background-size: 100% 100%;
  header {
    width: 100%;
    height: 50px;
    background: url('../../assets/avoidtest/dbczl@2x.png') no-repeat;
    background-size: 100% 100%;
    color: rgb(255, 255, 255);
    text-align: center;
    line-height: 50px;
    font-size: 20px;
    position: relative;
  }
  main {
    width: 100%;
    overflow: hidden;
    margin-top: 25px;

    .top {
      background: url('../../assets/avoidtest/tb@2x.png') no-repeat;
      background-size: 100% 100%;
      margin: 0 30px;
      // overflow: hidden;
      // height: 500px;
      .top1 {
        height: 30px;
        margin-top: 50px;
        font-size: 20px;
        color: white;
        // text-align: center;
      }
      .content {
        width: 70%;
        margin: 0 auto;
        margin-top: 50px;

        .th {
          width: 70px;
          height: 20px;
          background-color: #1b89fa;
          font-size: 12px;
          position: relative;
          top: -125px;
          left: -25px;
          border-radius: 20px;
          color: white;
          // text-align: center;
          line-height: 20px;
        }
        .qus {
          height: 450px;
          width: 100%;

          .title {
            width: 100%;
            line-height: 30px;
            text-align: left;
            text-indent: 2pt;
          }
          .a1 {
            padding-left: 5px;
            margin-top: 10px;
            display: inline-block;
            .van-radio {
              text-align: left;
              font-size: 13px;
              // margin-bottom: 10px 0;
              padding-bottom: 10px;
            }
            input[type='button'] {
              vertical-align: middle;
              height: 35px;
              width: 200px;
              border-radius: 20px;
              border: 1px solid white;
              // background-color: transparent;
            }
          }
        }
      }

      .jh {
        margin: 0 10px;
        // margin-top: 30px;
        color: white;
        overflow: hidden;
        .left {
          float: left;
          width: 100px;
          height: 40px;
          margin-left: 20px;
          border-radius: 20px;
          border: none;
        }
        .get,
        .right {
          float: right;
          width: 100px;
          height: 40px;
          margin-right: 20px;
          border-radius: 20px;
          border: none;
        }
      }
    }
  }
  .active {
    background-color: #1b89fa;
  }
  .huise {
    background-color: #91a3b2;
  }
  .trans {
    background-color: transparent;
  }
  .show {
    display: block;
  }
  .hidden {
    display: none;
  }
}
</style>
